<!--View/Elements/Transactions/index.ctp-->
<?php
App::uses('AppConstants', 'Model');
if (!isset($expense_categories)) {
	$expense_categories = $this->requestAction(array('controller' => 'categories', 'action' => 'index', AppConstants::TRANSACTION_TYPE_EXPENSE));
}
if (!isset($income_categories)) {
	$income_categories = $this->requestAction(array('controller' => 'categories', 'action' => 'index', AppConstants::TRANSACTION_TYPE_INCOME));
}

$category_icons_path = WWW_ROOT . 'img' . DS . 'icons' . DS . 'categories' . DS;
$category_icons = glob($category_icons_path . '{*.png, *.jpg, *.jpeg, *.gif}', GLOB_BRACE);

//Init params
$view_mode = isset($view_mode) ? $view_mode : 'week';
//ISO-8601 numeric representation of the day of the week. 1 (for Monday) through 7 (for Sunday)
$weekday = date('N');
$this_week_start = strtotime(($weekday - 1) . ' day ago');
$this_week_end = strtotime((7 - $weekday) . ' day');
$this_month_start = strtotime('first day of this month');
$this_month_end = strtotime('last day of this month');

$account = $this->requestAction(array('controller' => 'accounts', 'action' => 'get_active'));
$account_id = isset($account['Account']['id']) ? $account['Account']['id'] : null;
?>
<?php
//Categories select
$this->Html->script('jquery.ddslick.min', array('inline' => false));
$this->Html->css('jquery.ddslick', null, array('inline' => false));
//Datepicker
$this->Html->script('bootstrap-datepicker', array('inline' => false));
$this->Html->css('datepicker3', null, array('inline' => false));
?>
<input type="hidden" id="active_account_id" value="<?php echo $account_id; ?>" />

<input type="hidden" id="this_week_start" value="<?php echo date('Y-m-d 00:00:00', $this_week_start); ?>" />
<input type="hidden" id="this_week_end" value="<?php echo date('Y-m-d 23:59:59', $this_week_end); ?>" />
<input type="hidden" id="this_month_start" value="<?php echo date('Y-m-d 00:00:00', $this_month_start); ?>" />
<input type="hidden" id="this_month_end" value="<?php echo date('Y-m-d 23:59:59', $this_month_end); ?>" />

<div class="row">
    <div class="col-md-12">
        <div class="btn-group">
            <button id="btn-add-expense" type="button" class="btn btn-danger">Thêm khoản chi</button>
            <button id="btn-add-income" type="button" class="btn btn-success">Thêm khoản thu</button>
        </div>
        <div id="gr-view-mode-select" class="btn-group pull-right" data-toggle="buttons">
            <label class="btn btn-info<?php echo ('week' === $view_mode) ? ' active' : ''; ?>">
                <input type="radio" name="view_mode" value="week" id="view_mode_week"<?php echo ('week' === $view_mode) ? ' checked="checked"' : ''; ?>>Tuần
            </label>
            <label class="btn btn-success<?php echo ('month' === $view_mode) ? ' active' : ''; ?>">
                <input type="radio" name="view_mode" value="month" id="view_mode_month"<?php echo ('month' === $view_mode) ? ' checked="checked"' : ''; ?>>Tháng
            </label>
        </div>
    </div>
</div>

<div id="transaction_element">
</div>

<!-- Modal -->
<div class="modal fade" id="add-transaction-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Thêm khoản thu/chi</h4>
            </div>
            <div class="modal-body">
                <form id="add-transaction-form" class="form-horizontal" role="form">
                    <input type="hidden" class="required" id="inputType" name="data[Transaction][type]" />
                    <div class="form-group">
                        <label for="inputName" class="col-md-4 control-label">Nội dung</label>
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="inputName" name="data[Transaction][name]">
                        </div>
                    </div>
                    <div class="form-group" id="expense-categories-list">
                        <label for="inputCategory" class="col-md-4 control-label">Danh mục</label>
                        <div class="col-md-6">
                            <input type="hidden" class="form-control required" id="inputCategoryId" name="data[Transaction][category_id]">
                            <select class="inputCategory form-control" id="inputCategoryExpense">
								<?php
								foreach ($expense_categories as $category) {
									echo '<option value=' . $category['Category']['id'];
									echo ' data-imagesrc="' . $this->Html->assetUrl('img/icons/categories/' . $category['Category']['icon_path'], array('fullBase' => true)) . '"';
									echo '>' . $category['Category']['name'] . '</option>';
								}
								?>
                            </select>
                            <select class="inputCategory form-control" id="inputCategoryIncome">
								<?php
								foreach ($income_categories as $category) {
									echo '<option value=' . $category['Category']['id'];
									echo ' data-imagesrc="' . $this->Html->assetUrl('img/icons/categories/' . $category['Category']['icon_path'], array('fullBase' => true)) . '"';
									echo '>' . $category['Category']['name'] . '</option>';
								}
								?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputDate" class="col-md-4 control-label">Ngày</label>
                        <div class="col-md-6">
                            <input type="text" class="form-control datepicker required" id="inputDate" name="data[Transaction][date]">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="inputAmount" class="col-md-4 control-label">Số tiền</label>
                        <div class="col-md-6">
                            <input type="text" class="form-control required" id="inputAmount" name="data[Transaction][amount]">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button>
                <button id="btn-save-transaction" type="button" class="btn btn-success">Lưu</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->


<script>
	var edit_transaction_url = '<?php echo Router::url(array('controller' => 'transactions', 'action' => 'edit')); ?>';
	$(function() {
		//Load index element
		load_transaction_element("#transaction_element", null, null, $("input[name=view_mode]:checked").val());

		$(".datepicker").datepicker({
			format: "yyyy-mm-dd",
			weekStart: 1,
			todayBtn: "linked",
			language: "en",
			autoclose: true,
			todayHighlight: true
		});

		$(".inputCategory").each(function() {
			if (0 < $(this).children("option").length) {
				$(this).ddslick({
					height: 300,
					background: "#fff",
					onSelected: function(data) {
						$("#inputCategoryId").val(data.selectedData.value);
					}
				});
			}
		});

		$("#btn-add-expense").click(function() {
			$("#myModalLabel").text("Thêm khoản chi");
			$("#add-transaction-modal").modal("show");
			$("#inputCategoryExpense").show();
			$("#inputCategoryIncome").hide();

			reset_add_transaction_form();

			$("#inputType").val('<?php echo AppConstants::TRANSACTION_TYPE_EXPENSE; ?>');

			if (0 < $("#inputCategoryExpense option").length) {
				//In case user won't change category
				$("#inputCategoryId").val($("#inputCategoryExpense").data("ddslick").selectedData.value);
			}
		});

		$("#btn-add-income").click(function() {
			$("#myModalLabel").text("Thêm khoản thu");
			$("#add-transaction-modal").modal("show");
			$("#inputCategoryExpense").hide();
			$("#inputCategoryIncome").show();

			reset_add_transaction_form();

			$("#inputType").val('<?php echo AppConstants::TRANSACTION_TYPE_INCOME; ?>');

			if (0 < $("#inputCategoryIncome option").length) {
				//In case user won't change category
				$("#inputCategoryId").val($("#inputCategoryIncome").data("ddslick").selectedData.value);
			}
		});

		//Handle save transaction
		$("#btn-save-transaction").click(function() {
			//Validation
			var pass = true;
			var focus_input = null;
			$("#add-transaction-form .required").each(function() {
				var value = $.trim($(this).val());
				if (0 === value.length) {
					pass = false;
					if ((null === focus_input) && ($(this).is(":visible"))) {
						focus_input = $(this);
					}
					//In case of contains only spaces
					$(this).val('');
				}
			});

			if (pass) {
				//if name is missing, use category name
				var transaction_name = $.trim($("#add-transaction-form #inputName").val());
				if (0 === transaction_name.length) {
					if ($("#add-transaction-form #inputCategoryExpense").is(':visible')) {
						transaction_name = $("#add-transaction-form #inputCategoryExpense").data('ddslick').selectedData.text;
					} else if ($("#add-transaction-form #inputCategoryIncome").is(':visible')) {
						transaction_name = $("#add-transaction-form #inputCategoryIncome").data('ddslick').selectedData.text;
					}
				}
				$.post(
						edit_transaction_url,
						{
							Transaction: {
								account_id: $("#active_account_id").val(),
								type: $("#add-transaction-form #inputType").val(),
								name: transaction_name,
								category_id: $("#add-transaction-form #inputCategoryId").val(),
								date: $("#add-transaction-form #inputDate").val(),
								amount: $("#add-transaction-form #inputAmount").val(),
							}
						},
				function(data, textStatus, jqXHR) {
					if (true === data.status) {
						$("#add-transaction-modal").modal("hide");
						load_transaction_element("#transaction_element", null, null, $("input[name=view_mode]:checked").val());
					}
				},
						'json'
						);
			} else {
				alert('Vui lòng nhập đầy đủ thông tin.');
				if (null !== focus_input) {
					focus_input.focus();
				}
			}
		});

		//Reload on view mode changed
		$("input[name=view_mode]").change(function() {
			load_transaction_element("#transaction_element", null, null, null);
		});
	});

	function reset_add_transaction_form() {
		$("#add-transaction-form #inputName").val("");

		var today = new Date();
		var today_str = today.getFullYear() + '-';
		today_str += (today.getMonth() < 9) ? '0' + (today.getMonth() + 1) : (today.getMonth() + 1);
		today_str += '-';
		today_str += (today.getDate() < 10) ? ('0' + today.getDate()) : today.getDate();
		$("#add-transaction-form #inputDate").val(today_str);

		$("#add-transaction-form #inputCategoryExpense").ddslick("select", {index: 0});
		$("#add-transaction-form #inputCategoryIncome").ddslick("select", {index: 0});
		$("#add-transaction-form #inputAmount").val("");
	}

	function load_transaction_element(update_target, base_date, modifier, view_mode) {
		var load_transactions_url = '<?php echo Router::url(array('controller' => 'transactions', 'action' => 'ajax_index'), true); ?>';
		var active_account_id = $("#active_account_id").val();

		//If view_mode is not set, find view_mode input
		if ((null === view_mode) || (undefined === view_mode)) {
			view_mode = $("input#view_mode_month").prop("checked") ? "month" : "week";
		}

		var params = {
			"account_id": active_account_id,
			"category_id": null,
			"base_date": base_date,
			"modifier": modifier,
			"view_mode": view_mode,
		};
		$.post(
				load_transactions_url,
				params,
				function(data, textStatus, jqXHR) {
					$(update_target).html(data);
				}
		);
	}
</script>